﻿using CodeFinder.Common.Entities;
using CodeFinder.Common.Interfaces;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeFinder.Bussiness.Concretes {
    public class PostService : IPostService {
        private IRepository<Post> m_postRepository;
        private IRepository<Comment> m_commentRepository;
        public PostService(DbContext context) {
            m_postRepository = new Repository<Post>(context);
            m_commentRepository = new Repository<Comment>(context);
        }
        public PostService()
            : this(new CodeFinderModelContainer()) {

        }
        public int CountPost() {
            return m_postRepository.GetAll().Count();
        }

        public Common.Entities.Post FindPostById(int id) {
            return m_postRepository.GetById(id);
        }

        public IQueryable<Common.Entities.Post> Posts {
            get {
                return m_postRepository.GetAll();
            }
        }


        public void Save(Post post) {
            var dbPost = m_postRepository.GetById(post.Id);
            if (dbPost == null) {
                m_postRepository.Save(post);
            } else {
                dbPost.Title = post.Title;
                dbPost.Content = post.Content;
                dbPost.Category = post.Category;
            }

            m_postRepository.Commit();
        }

        
        public void Delete(int id) {
            var post = m_postRepository.GetById(id);
            m_postRepository.Delete(post);
            m_postRepository.Commit();
        }


        public void AddComment(Comment comment) {
            m_commentRepository.Save(comment);
            m_commentRepository.Commit();
        }


        public int CountComments(int postId) {
            return m_commentRepository.GetAll().Count(x => x.PostId == postId);
        }
    }
}
